<template>
  <view class="page-wrapper">
    <view class="content-wrapper">
      <view class="appointment-page">
        <!-- 日历部分 -->
        <view class="calendar-section">
          <view class="calendar-header">
            <text class="month-title">{{ currentYear }}年{{ currentMonth }}月</text>
            <view class="month-switcher">
              <text @tap="changeMonth(-1)" class="switch-btn">上个月</text>
              <text @tap="changeMonth(1)" class="switch-btn">下个月</text>
            </view>
          </view>
          <view class="weekdays">
            <text v-for="day in ['日','一','二','三','四','五','六']" :key="day">{{ day }}</text>
          </view>
          <view class="days-grid">
            <view 
              v-for="(day, index) in calendarDays" 
              :key="index"
              :class="[
                'day-item',
                day.isPast ? 'past' : '',
                day.isToday ? 'today' : '',
                day.date === selectedDate ? 'selected' : '',
                !day.date ? 'empty' : '',
                day.isDisabled ? 'disabled' : ''
              ]"
              @tap="selectDate(day)"
            >
              <text>{{ day.date?.getDate() || '' }}</text>
            </view>
          </view>
        </view>

        <!-- 时间段选择 -->
        <view class="time-slots-section">
          <text class="section-title">选择时间段</text>
          <view class="time-slots-grid">
            <view 
              v-for="(slot, index) in timeSlots" 
              :key="index"
              :class="[
                'time-slot-item',
                !slot.available ? 'disabled' : '',
                selectedTimeSlot === index ? 'selected' : ''
              ]"
              @tap="selectTimeSlot(index, slot)"
            >
              <text class="time-text">{{ slot.time }}</text>
              <text class="status-text" :class="{ 'unavailable': !slot.available }">
                {{ slot.available ? '可预约' : '已预约' }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-button">
      <button 
        class="submit-btn" 
        :disabled="!canSubmit"
        @tap="submitAppointment"
      >
        确认预约
      </button>
    </view>

    <!-- 登录弹框 -->
    <login-modal
      ref="loginModal"
      :show="showLoginModal"
      @login-success="onLoginSuccess"
    />
  </view>
</template>

<script>
import config from '@/config/config.js'
import LoginModal from '@/components/login-modal/index.vue'

export default {
  components: {
    'login-modal': LoginModal
  },

  data() {
    return {
      showLoginModal: false,
      productId: '',
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      calendarDays: [],
      selectedDate: null,
      selectedTimeSlot: null,
      timeSlots: [
        { time: '09:00-11:00', available: true },
        { time: '11:00-13:00', available: true },
        { time: '13:00-15:00', available: true },
        { time: '15:00-17:00', available: true },
        { time: '17:00-19:00', available: true },
        { time: '19:00-21:00', available: true }
      ]
    }
  },

  computed: {
    canSubmit() {
      return this.selectedDate && this.selectedTimeSlot !== null
    }
  },

  onLoad(options) {
    if (options.productId) {
      this.productId = options.productId
      this.selectedDate = new Date()
      this.initCalendar()
      this.getAppointmentData()
    }
  },

  methods: {
    // 初始化日历
    initCalendar() {
      const today = new Date()
      const currentDate = new Date(this.currentYear, this.currentMonth - 1, 1)
      const firstDay = currentDate.getDay()
      const lastDay = new Date(this.currentYear, this.currentMonth, 0).getDate()
      const maxDate = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000)
      
      let days = Array(firstDay).fill({})
      
      for (let i = 1; i <= lastDay; i++) {
        const date = new Date(this.currentYear, this.currentMonth - 1, i)
        days.push({
          date,
          isPast: date < new Date(today.setHours(0,0,0,0)),
          isToday: date.toDateString() === today.toDateString(),
          isDisabled: date > maxDate
        })
      }
      
      this.calendarDays = days
    },

    // 切换月份
    changeMonth(delta) {
      const newDate = new Date(this.currentYear, this.currentMonth - 1 + delta, 1)
      this.currentYear = newDate.getFullYear()
      this.currentMonth = newDate.getMonth() + 1
      this.initCalendar()
    },

    // 选择日期
    async selectDate(day) {
      if (!day.date || day.isPast || day.isDisabled) return
      this.selectedDate = day.date
      this.selectedTimeSlot = null
      await this.getAppointmentData()
    },

    // 获取预约数据
    async getAppointmentData() {
      if (!this.selectedDate) return
      
      try {
        console.log('开始获取预约数据')
        const res = await this.$http.post(config.api.appointment.queryAppointments, {
          productId: this.productId,
          apointTime: this.formatDate(this.selectedDate)
        })
        
        console.log('获取预约数据响应:', res.data)
        
        if (res.data.code === 200) {
          const bookedSlots = res.data.data || []
          this.updateTimeSlots(bookedSlots)
          console.log('更新后的时间槽:', this.timeSlots)
        } else if (res.data.code === 400) {
          this.showLoginModal = true
          this.$refs.loginModal.startLogin()
        }
      } catch (err) {
        console.error('获取预约数据失败:', err)
        uni.showToast({
          title: '获取预约数据失败',
          icon: 'none'
        })
      }
    },

    // 更新时间段状态
    updateTimeSlots(bookedSlots) {
      this.timeSlots = this.timeSlots.map(slot => ({
        ...slot,
        available: !bookedSlots.includes(slot.time)
      }))
    },

    // 选择时间段
    selectTimeSlot(index, slot) {
      if (!slot.available) {
        uni.showToast({
          title: '该时段已被预约',
          icon: 'none'
        })
        return
      }
      this.selectedTimeSlot = index
    },

    // 提交预约
    async submitAppointment() {
      if (!this.canSubmit) return

      try {
        console.log('开始提交预约')
        const res = await this.$http.post(config.api.appointment.appoint, {
          productId: this.productId,
          apointTime: this.formatDate(this.selectedDate),
          timeSlot: this.timeSlots[this.selectedTimeSlot].time,
		  times:"1",
		  apointType:"6"
        })
        
        if (res.data.code === 200||res.data.code === 201) {
          console.log('预约提交成功，准备刷新数据')
          
          // 确保异步操作按顺序执行
          try {
            await this.getAppointmentData()
            console.log('预约数据刷新完成')
            
            uni.showToast({
              title: '预约成功',
              icon: 'success'
            })

            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } catch (refreshError) {
            console.error('刷新预约数据失败:', refreshError)
          }
        } else if (res.data.code === 400) {
          this.showLoginModal = true
          this.$refs.loginModal.startLogin()
        } else {
          throw new Error(res.data.message || '预约失败')
        }
      } catch (err) {
        console.error('预约失败:', err)
        uni.showToast({
          title: err.message || '预约失败',
          icon: 'none'
        })
      }
    },

    // 登录成功回调
    async onLoginSuccess() {
      this.showLoginModal = false
      await this.getAppointmentData()
    },

    // 格式化日期
    formatDate(date) {
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.page-wrapper {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

.content-wrapper {
  flex: 1;
  padding-bottom: 180rpx; // 为底部按钮预留空间
}

.appointment-page {
  padding: 30rpx;
}

.calendar-section {
  background: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.month-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #000000;
}

.month-switcher {
  display: flex;
  gap: 20rpx;
  
  .switch-btn {
    font-size: 28rpx;
    color: #666666;
    padding: 10rpx 20rpx;
    
    &:active {
      opacity: 0.7;
    }
  }
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  margin-bottom: 20rpx;
  
  text {
    font-size: 24rpx;
    color: #999999;
  }
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10rpx;
}

.day-item {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #333333;
  border-radius: 8rpx;
  
  &.past, &.disabled {
    color: #cccccc;
    background: #f5f5f5;
  }
  
  &.today {
    color: #000000;
    font-weight: 500;
    border: 2rpx solid #000000;
  }
  
  &.selected {
    background: #000000;
    color: #ffffff;
  }
  
  &.empty {
    pointer-events: none;
  }
}

.time-slots-section {
  background: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #000000;
  margin-bottom: 30rpx;
}

.time-slots-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.time-slot-item {
  height: 160rpx;
  padding: 30rpx;
  background: #ffffff;
  border: 1rpx solid #eeeeee;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  
  &.disabled {
    background: #f8f8f8;
  }
  
  &.selected {
    background: #000000;
    border-color: #000000;
    
    .time-text, .status-text {
      color: #ffffff;
    }
  }
  
  .time-text {
    font-size: 32rpx;
    font-weight: 500;
    color: #333333;
    margin-bottom: 20rpx;
  }
  
  .status-text {
    font-size: 26rpx;
    color: #00b578;
    
    &.unavailable {
      color: #ff4d4f;
    }
    
    &.available {
      color: #00b578;
    }
  }
}

.bottom-button {
  position: fixed;
  left: 30rpx;
  right: 30rpx;
  bottom: 40rpx;
  padding: 20rpx 0;
  background: #ffffff;
  
  .submit-btn {
    width: 100%;
    height: 90rpx;
    background: #000000;
    color: #ffffff;
    border-radius: 45rpx;
    font-size: 32rpx;
    font-weight: 500;
    
    &:disabled {
      background: #cccccc;
    }
  }
}
</style>
